package live.jipiao.dao;

import java.sql.SQLException;
import java.util.List;
import java.util.Map;

import live.common.AirParam;
import live.common.DBHelper;
import live.common.ErrorException;
import live.common.Page;
import live.common.Verifystring;
import live.jipiao.dao.XmlFormart;
import live.jipiao.entity.AirOrder;
import live.jipiao.entity.Itinerary;

import org.dom4j.Document;
import org.dom4j.DocumentException;

public class AirItinerary {

	private XmlFormart xfm = XmlFormart.getInstance();
	private Verifystring verify = Verifystring.getInstance();
	private DBHelper dh = null;
	private StringBuffer sql = null;
	/**
	 * 返回行程单编号
	 * 
	 * @param item
	 * @return
	 * @throws ErrorException
	 */
	public Itinerary returnItineraryNo(Itinerary item, String memberNum)
			throws ErrorException {
		String resultItinNo = null;
		Itinerary itinerary = null;
		Map<String, String> map = xfm.returnPublicPostData(AirParam.ITIN
				.toString());
		String itineraryInfo = returnItineraryInfo(item);
		map.put("itineraryInfo", itineraryInfo);
		map.put("orderNos", item.getOrderNo());
		String passengerNames = returnPassengers(item.getOrderNo());
		item.setPassengerNames(passengerNames);
		map.put("passengerNames", passengerNames);
		String sign = verify.returnAirMd5Hex(map);
		map.put("sign", sign);
		resultItinNo = new WebServicesSub().returnResult(map);
		Document doc;
		try {
			doc = xfm.xmlToDocument(resultItinNo.trim());
			if (xfm.returnSingleNode(doc, "//is_success").trim()
					.equals("T")) {
				resultItinNo = xfm.returnSingleNode(doc, "//itineraryNo")
						.trim();
				itinerary = item;
				itinerary.setItineraryNo(resultItinNo);
				saveItin(itinerary, memberNum);
			} else {
				itinerary = null;
				throw new ErrorException(AirItinerary.class + ";Method:"
						+ new Exception().getStackTrace()[0].getMethodName()
						+ "API Error" + xfm.returnSingleNode(doc, "//error"));
			}
		} catch (DocumentException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		return itinerary;
	}

	/**
	 * 组装行程单信息
	 * 
	 * @param item
	 * @return
	 */
	private String returnItineraryInfo(Itinerary item) {
		String result = new StringBuffer("1").append("^")
				.append(item.getName().trim()).append("^").append(item.getPhone().trim())
				.append("^").append(item.getZip().trim()).append("^").append(
						item.getAddress().trim()).toString();
		return result;
	}

	/**
	 * 组装订单乘客信息
	 * 
	 * @param ordernos
	 * @return
	 */
	private String returnPassengers(String ordernos) {
		dh = DBHelper.getInstance();
		StringBuffer result = new StringBuffer();
		try {
			ordernos = ordernos.replaceAll("\\^", ",");
			List records = dh.queryRecordsMap("{call queryPassengersName(?)}",
					new Object[] { ordernos });
			String record = null;
			for (int i = 0; i < records.size(); i++) {
				Map map = (Map) records.get(i);
				record = map.get("passengers").toString();
				if (record.contains("|") == true) {
					String[] new_record = record.split("\\|");
					for (int j = 0; j < new_record.length; j++) {
						result.append(new_record[j].split("\\^")[0].trim());
						if (j != new_record.length - 1) {
							result.append("|");
						}
					}
				} else {
					result.append(record.split("\\^")[0].trim());
				}
				if (i != records.size() - 1) {
					result.append("^");
				}
			}
		} catch (SQLException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		dh.close();
		return result.toString();
	}
	
	

	/**
	 * 行程单订单数据信息
	 * 
	 * @param orderNos
	 * @return
	 * @throws SQLException
	 */
	public List<AirOrder> returnOrdersForItin(String orderNos)
			throws SQLException {
		dh = DBHelper.getInstance();
		orderNos = orderNos.replaceAll("\\^", ",");
		String sql = "{call queryPlaneOrderForItin(?)}";
		dh.setBeanClass(AirOrder.class);
		List<AirOrder> orders = dh.queryRecords(sql, new Object[] { orderNos });
		dh.close();
		return orders;
	}

	/**
	 * 行程单支付
	 * 
	 * @param itineraryNo
	 * @return
	 */
	private String paySuccessItin(String itineraryNo) {
		Map<String, String> map = xfm
				.returnPublicPostData(AirParam.ITIN_AUTOPAY.toString());
		map.put("itineraryNo", itineraryNo);
		map.put("autopaymode", "1");
		map.put("paytype", "A");
		map.put("sign", verify.returnAirMd5Hex(map));
		String result = null;
		result = WebServicesSub.getInstance().returnResult(map);
		return result;
	}
	
	public static void main(String[] args) {
		try {
			System.out.print(new AirItinerary().returnAutoPayState("201110121710561356"));
		} catch (DocumentException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		
	}
	
	
	public boolean returnAutoPayState(String itineraryNo) throws DocumentException{
		String postResult = paySuccessItin(itineraryNo);
		System.out.print(postResult);
		Document doc = xfm.xmlToDocument(postResult.trim());
		if (xfm.returnSingleNode(doc, "//is_success").toUpperCase().trim()
				.equals("T")) {
			updateItinState(itineraryNo,1);
			return true;
		}else{
			//updateItinState(itineraryNo,2);
			return false;
		}
	}
	
	
	/**
	 * 获取行程单信息
	 * @param id
	 * @return
	 * @throws SQLException
	 */
	public Itinerary getItinerary(int id) throws SQLException{
		dh=DBHelper.getInstance();
		dh.setBeanClass(Itinerary.class);
		Itinerary itin = (Itinerary)dh.query("SELECT * FROM Plan_Itinerary WHERE 1=1 AND ID="+id);
		dh.close();
		return itin;
	}
	
	public Itinerary getItineraryForNum(String itinNo) throws SQLException{
		dh=DBHelper.getInstance();
		dh.setBeanClass(Itinerary.class);
		Itinerary itin = (Itinerary)dh.query("SELECT * FROM Plan_Itinerary WHERE 1=1 AND itineraryNo='"+itinNo+"'");
		dh.close();
		return itin;
	}

	/**
	 * 添加新纪录
	 * 
	 * @param item
	 * @throws ErrorException
	 */
	private void saveItin(Itinerary item, String memberNum)
			throws ErrorException {
		String sql = "{call saveItinerary(?,?,?,?,?,?,?,?,?)}";
		Object[] args = new Object[9];
		args[0] = item.getAddress();
		args[1] = item.getName();
		args[2] = item.getZip();
		args[3] = item.getPhone();
		args[4] = item.getOrderNo();
		args[5] = item.getItineraryNo();
		args[6] = item.getPassengerNames();
		args[7] = item.getPayTotal();
		args[8] = memberNum;
		DBHelper dh = DBHelper.getInstance();
		try {
			dh.update(sql, args);
		} catch (SQLException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
			throw new ErrorException(AirItinerary.class + ";Method:"
					+ new Exception().getStackTrace()[0].getMethodName()
					+ "throws SQLException" + e.getMessage());
		}
		dh.close();
	}
	private void updateItinState(String itineraryNo,int state){
		String sql = new StringBuffer("UPDATE Plan_Itinerary SET status=").append(state)
		.append(" WHERE itineraryNo='").append(itineraryNo).append("'").toString();
		dh=DBHelper.getInstance();
		try {
			dh.update(sql);
		} catch (SQLException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}finally{dh.close();}
		
	}
	/**
	 * 支付描述信息
	 * @param item
	 * @return
	 */
	public static String returnItinSubject(Itinerary item) {
		return new StringBuffer("行程单【").append(item.getItineraryNo()).append("】,")
			.append(Float.parseFloat(item.getPayTotal()))
				.toString();
	}
	
	/**
	 * 获取行程单信息
	 * @param memberNo
	 * @param page
	 * @return
	 * @throws SQLException
	 */
	public List<Itinerary> queryItinerarys(String memberNo,Page page) throws SQLException{
		dh = DBHelper.getInstance();
		String execSql = "{call pro_Common_PageView(?,?,?,?)}";
		sql = new StringBuffer("SELECT * FROM Plan_Itinerary WHERE 1=1 AND memberNo='").append(memberNo).append("' ");
		sql.append(" order by creatTime desc ");
		Object[] args = new Object[4];
		args[0]=sql.toString();
		args[1]=page.getPageIndex();
		args[2]=page.getPageSize();
		args[3]="";
		Itinerary item = null;
		dh.setBeanClass(Itinerary.class);
		List orderList = dh.queryRecords(execSql, args);
		page.setRecordCount(dh.returnOutParam(execSql, args));
//		String execSql = "{call returnNotApplyItinOrders(?)}";
//		List<Itinerary> itinerayrs = dh.queryRecords(execSql, new Object[]{memberNo});
		dh.close();
		return orderList;
	}
}
